package com.chinaunicom.emergency.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Set;

/**
 * @author liliang
 * @date 2019-12-13
 */
@Log4j2
public class IpUtil {

    private static String systemIp = null;
    private static String serverPort = null;

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    if(inet != null){
                        ipAddress = inet.getHostAddress();
                    }
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }


    public static String getHostIp(){
        try{
            if(StringUtils.isNotBlank(systemIp)){
                return systemIp;
            }
            for(Enumeration<NetworkInterface> i = NetworkInterface.getNetworkInterfaces(); i.hasMoreElements(); ) {
                NetworkInterface ni = i.nextElement();
                if(ni.getDisplayName().indexOf("eth0") != -1){
                    for(Enumeration<InetAddress> j = ni.getInetAddresses(); j.hasMoreElements(); ) {
                        String ip = j.nextElement().getHostAddress();
                        if(ip.indexOf(":") == -1){
                            systemIp = ip;
                            return ip;
                        }
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return "127.0.0.1";
    }

    public static String getTomcatPort() {
        if(StringUtils.isNotBlank(serverPort)){
            return serverPort;
        }
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = null;
        try {
            objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        String port = objectNames.iterator().next().getKeyProperty("port");
        serverPort = port;
        return serverPort;
    }

    public static String getSystemIpPort(){
        return getHostIp() + ":" + getTomcatPort();
    }



    public static void  main(String[] args) throws UnknownHostException {
        log.info(getSystemIpPort());
    }

}